package com.xc.hotelmgr.webapi.modules.op.controller;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.hotelmgr.webapi.common.annotation.SysLog;
import com.xc.hotelmgr.webapi.modules.dt.entity.DtOrderChannelsEntity;
import com.xc.hotelmgr.webapi.modules.dt.entity.StoreEntity;
import com.xc.hotelmgr.webapi.modules.dt.entity.StorePfEntity;
import com.xc.hotelmgr.webapi.modules.dt.service.DtOrderChannelsService;
import com.xc.hotelmgr.webapi.modules.dt.service.StorePfService;
import com.xc.hotelmgr.webapi.modules.dt.service.StoreService;
import com.xc.hotelmgr.webapi.modules.mq.service.HotelToMQService;
import com.xc.hotelmgr.webapi.modules.op.entity.FeignResult;
import com.xc.hotelmgr.webapi.modules.op.entity.TaskHotelList;
import com.xc.hotelmgr.webapi.modules.op.service.MqFeignService;
import com.xc.hotelmgr.webapi.modules.op.service.MtFeignService;
import com.xc.hotelmgr.webapi.modules.op.service.XCFeignServiceOnece;
import com.xc.hotelmgr.webapi.modules.sys.controller.AbstractController;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.xc.hotelmgr.webapi.modules.op.entity.TaskStatusEntity;
import com.xc.hotelmgr.webapi.modules.op.service.TaskStatusService;
import com.xc.hotelmgr.webapi.common.utils.PageUtils;
import com.xc.hotelmgr.webapi.common.utils.R;



/**
 * 任务状态表（前端与服务交互）
 *
 * @author kemmy
 * @email kemmy@gmail.com
 * @date 2020-10-13 16:25:44
 */
@RestController
@RequestMapping("op/taskstatus")
@RequiredArgsConstructor
public class TaskStatusController extends AbstractController {

    private final TaskStatusService taskStatusService;

    private final StorePfService storePfService;

    private final StoreService storeService;

    private final MtFeignService mtFeignService;

    private final MqFeignService mqFeignService;

    private final XCFeignServiceOnece xcFeignServiceOnece;

    private final DtOrderChannelsService dtOrderChannelsService;

    @Autowired
    private HotelToMQService hotelToMQService;

    @SysLog
    @RequestMapping("/pf")
    @RequiresPermissions("op:taskstatus:list")
    public R listPf(@RequestParam Map<String, Object> params){
        params.put("dtId",getUserDtId());
        List<StorePfEntity> spfs = storePfService.getBaseMapper().selectList(new QueryWrapper<StorePfEntity>());
        return R.ok().put("spfs",spfs);
    }

    @SysLog
    @RequestMapping("/store")
    @RequiresPermissions("op:taskstatus:list")
    public R listStore(@RequestParam Map<String, Object> params){
        params.put("dtId",getUserDtId());
        List<StoreEntity> list = storeService.queryByDtId(params);
        return R.ok().put("list", list);
    }
    /**
     * 列表
     */
    @SysLog
    @RequestMapping("/list")
    @RequiresPermissions("op:taskstatus:list")
    public R list(@RequestParam Map<String, Object> params){
        String taskCode = (String)params.get("taskCode");
        // 如果是查询店铺推送及上下架任务信息，则只能查看分销商自己的店铺的任务信息
        if(StringUtils.equals("STOREHOTEL",taskCode)){
            params.put("dtId",getUserDtId().toString());
        }
        PageUtils page = taskStatusService.sqlQueryPage(params);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @SysLog
    @RequestMapping("/info/{id}")
    @RequiresPermissions("op:taskstatus:info")
    public R info(@PathVariable("id") Long id){
		TaskStatusEntity taskStatus = taskStatusService.getById(id);

        return R.ok().put("taskStatus", taskStatus);
    }

    /**
     * 保存
     */
    @SysLog
    @RequestMapping("/save")
    @RequiresPermissions("op:taskstatus:save")
    public R save(@RequestBody TaskStatusEntity taskStatus){
		taskStatusService.save(taskStatus);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog
    @RequestMapping("/update")
    @RequiresPermissions("op:taskstatus:update")
    public R update(@RequestBody TaskStatusEntity taskStatus){
		taskStatusService.updateById(taskStatus);

        return R.ok();
    }

    /**
     * 删除
     */
    @SysLog
    @RequestMapping("/delete")
    @RequiresPermissions("op:taskstatus:delete")
    public R delete(@RequestBody Long[] ids){
		taskStatusService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 店铺初始化(meit 从store里面取了dtId)
     * @param params
     * @return
     */
    @SysLog
    @RequestMapping("/init/store")
    @RequiresPermissions("op:init:store")
    public R initStore(@RequestParam Map<String, Object> params){
        Integer storId = Integer.valueOf((String) params.get("storId"));
        try {
            hotelToMQService.sendAll(storId);
            return R.ok();
        }catch (Exception ex){
            return R.error(ex.getMessage());
        }
    }

    /**
     * 店铺酒店上下架(meit 从store里面取了dtId)
     * @param params
     * @return
     */
    @SysLog
    @RequestMapping("/updown/store")
    @RequiresPermissions("op:updown:store")
    public R upDownStore(@RequestParam Map<String, Object> params){
        String storId = (String) params.get("storId");
        String status = (String) params.get("status");
        try{
            hotelToMQService.upDown(Integer.valueOf(storId),Integer.valueOf(status));
            return R.ok();
        }catch (Exception ex){
            return R.error(ex.getMessage());
        }
    }


    /**
     * 美团酒店初始化（全量酒店拉取）
     */
    @SysLog("美团酒店初始化")
    @RequestMapping("/init/hotel/mt")
    @RequiresPermissions("op:init:hotel")
    public R initHotelMT(@RequestParam Map<String, Object> params) {
        String taskId = "-10";
        String pTaskId = (String) params.get("taskId");
        if(!StringUtils.isEmpty(pTaskId)) {
            taskId = pTaskId;
        }
        Long cnt = taskStatusService.taskCnt();
        if(cnt > 0){
            return R.error("正在执行拉取、上传的任务...，请等待任务完成后再执行");
        }
        FeignResult result = mtFeignService.getHtIds(Long.valueOf(taskId));
        if(result.getCode() == 0){
            return R.ok();
        }else {
            return  R.error(result.getMessage());
        }
    }

    /**
     * 携程酒店初始化（全量拉取酒店）
     * @param params
     * @return
     */
    @SysLog("携程酒店初始化")
    @RequestMapping("/init/hotel/xc")
    @RequiresPermissions("op:init:hotel")
    public R initHotelXC(@RequestParam Map<String, Object> params) {
        Integer dtId = getUserDtId();
        Map<String, Object> map = new HashMap<>();
        map.put("dtId", dtId);
        List<StoreEntity> stores = storeService.queryByDtId(map);
        // 随机取其中一个
        Random random = new Random();
        int n = random.nextInt(stores.size());
        StoreEntity storeEntity = stores.get(n);
        Integer storeId = storeEntity.getId();
        DtOrderChannelsEntity dtOrderChannelsEntity = dtOrderChannelsService.getByStoreIdAndChanel(storeId, 1);
        TaskHotelList taskHotelList = new TaskHotelList();
        taskHotelList.setAID(Integer.valueOf(dtOrderChannelsEntity.getAccessKey()));
        taskHotelList.setSID(dtOrderChannelsEntity.getSid());
        taskHotelList.setTaskCode(0L);
        taskHotelList.setKEY(dtOrderChannelsEntity.getSecretKey());
        xcFeignServiceOnece.staticCityAll(taskHotelList);
        return R.ok("携程酒店初始化开始。。。");
    }

    /**
     * 酒店初始化暂停
     */
    @SysLog
    @RequestMapping("/init/hotel/pause")
    @RequiresPermissions("op:init:hotel")
    public R initHotelPause(@RequestParam Map<String, Object> params) {
        String id = (String) params.get("id");
        String pause = (String) params.get("pause");
        FeignResult result = mqFeignService.getHtIdOnOff(Integer.valueOf(pause));
        if(result.getCode() != 0){
            return R.error("调用接口失败");
        }
        TaskStatusEntity taskStatusEntity = new TaskStatusEntity();
        taskStatusEntity.setId(Long.valueOf(id));
        taskStatusEntity.setPause(Integer.valueOf(pause));
        taskStatusService.saveOrUpdate(taskStatusEntity);
        return R.ok();
    }
}
